/**
 * 
 */
package com.ihome.framework.core.event.handler;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

//import com.ihome.framework.core.event.Account;
import com.ihome.framework.core.event.PayoutDataEvent;
import com.ihome.framework.core.event.SpringTestCase;
import com.ihome.framework.core.event.IHomeEventBusHandler.EventBusWorkHandler;
import com.ihome.framework.core.event.command.FrozenAccountCommand;
import com.ihome.framework.core.event.command.FundOrderUpdateStatusCommand;
import com.ihome.framework.core.event.command.TallyAccountCommand;
import com.ihome.framework.core.event.command.lua.TallyAccountLuaCommandScript;

/**
 * @author zww
 *
 */
@Component
public  class PayoutDataTallyHandler extends EventBusWorkHandler<PayoutDataEvent>{
    
    @Resource
    private TallyAccountLuaCommandScript tallyAccountLuaCommandScript;
    
    /* (non-Javadoc)
     * @see com.ihome.framework.core.event.IHomeEventBusHandler#onEvent(com.ihome.framework.core.event.IHomeEventBusHandler.EventDto)
     */
    @Override
    public void handler(PayoutDataEvent e,long sequence,boolean endOfBatch) throws Exception {
        long threadId = Thread.currentThread().getId(); // 获取当前线程id
        String accountNo = e.getAccountNo();
        Integer money = e.getMoney();
        try{
            
            if(((Long)tallyAccountLuaCommandScript.execute(new String[]{redisClient.getNamespace()+"Account-"+accountNo}, money.toString())).intValue() == 1){
                SpringTestCase.LOG.incrementAndGet();
                LOGGER.info(String.format("UUID %s | Thread Id %s 解冻金额并记账[account:%s|status:TALLY] ........",e.getRequestId(),threadId, 
                        ""));
                e.addCommand(new FundOrderUpdateStatusCommand(e.getRequestId(),"TALLY"));
                e.addCommand(new TallyAccountCommand(e.getRequestId(), (long)e.getMoney(), accountNo));
                
            }else{
                LOGGER.info(String.format("UUID %s | Thread Id %s 账户余额不足记账错误[account:%s|status:ERROR] ........",e.getRequestId(),threadId,
                        ""));
            }
        }finally {
            try{
                flush();
            }catch (Throwable ex) {
                ex.printStackTrace();
            }
        }
    }
}